package com.kaishengit.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.kaishengit.dto.Message;
import com.kaishengit.pojo.Customer;
import com.kaishengit.pojo.Progress;
import com.kaishengit.pojo.User;
import com.kaishengit.service.CustomerService;
import com.kaishengit.service.ProgressService;
import com.kaishengit.service.UserService;
import com.kaishengit.util.Page;
import com.kaishengit.util.Strings;

@Controller
@RequestMapping("/progress")
public class ProgressController {
	
	//获取配置文件中的文件存储路径
	@Value("${user.saveDir}")
	private String saveDir;
	@Inject
	private UserService userService;
	@Inject
	private CustomerService customerService;
	@Inject
	private ProgressService progressService;

	/**
	 * 跟进首页
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list(@RequestParam(required = false, defaultValue = "") String userid,
			@RequestParam(required = false, defaultValue = "") String progress,
			@RequestParam(required = false, defaultValue = "") String date,
			@RequestParam(required = false, defaultValue = "") String context,
			@RequestParam(required = false, defaultValue = "1") String p, Model model) {
		progress = Strings.toUTF8(progress);
		date = Strings.toUTF8(date);
		context = Strings.toUTF8(context);

		List<User> userList = userService.findAllUser();
		List<Customer> customerList = customerService.findCustomerByCurrentUser();

		Page<Progress> page = progressService.findProgressByPageAndParam(userid, progress, date, context, p);

		model.addAttribute("userList", userList);
		model.addAttribute("page", page);
		model.addAttribute("customerList", customerList);
		model.addAttribute("userid", userid);
		model.addAttribute("progress", progress);
		model.addAttribute("date", date);
		model.addAttribute("context", context);
		return "progress/list";
	}

	/**
	 * 保存新跟进记录
	 * @param request
	 * @param progress
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/new", method = RequestMethod.POST)
	public String save(HttpServletRequest request, Progress progress, @RequestParam MultipartFile file,
			RedirectAttributes redirectAttributes) {

		// 从配置文件中获取文件存储路径
		String savedDir = saveDir;
		try {
			progressService.saveNewProgress(progress, file, savedDir);
			redirectAttributes.addFlashAttribute("message", new Message(Message.SUCCESS, "添加客户跟进信息成功"));
		} catch (IOException e) {
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", new Message(Message.ERROR, "添加客户跟进信息失败"));
		}
		return "redirect:/progress";
	}

	
	/**
	 * 进行文件下载
	 * @param fileName
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public String downLoadFile(@RequestParam("fileName") String fileName, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {

		// 用于记录以完成的下载的数据量，单位是byte
		long downloadedLength = 0l;

		try {
			// 获取文件所在的路径
			String downPath = saveDir + "/" + fileName;
			File file = new File(downPath);
			// 设置响应头和客户端保存文件名
			fileName = new String(fileName.getBytes(), "ISO-8859-1");
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

			// 打开本地文件流
			InputStream inputStream = new FileInputStream(file);

			// 激活下载操作
			OutputStream os = response.getOutputStream();

			// 循环写入输出流
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
				downloadedLength += b.length;
			}
			// 这里主要关闭。
			os.close();
			inputStream.close();
		} catch (UnsupportedEncodingException e1) {
			redirectAttributes.addFlashAttribute("message", new Message(Message.ERROR, e1.getMessage()));
			e1.printStackTrace();
			return "redirect:/progress";
		} catch (IOException e) {
			redirectAttributes.addFlashAttribute("message", new Message(Message.ERROR, "系统找不到指定的文件,文件不存在"));
			return "redirect:/progress";
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", new Message(Message.ERROR, "文件下载失败！！！"));
			return "redirect:/progress";
		}
		return "redirect:/progress";
	}
}
